package com.xiaomengkuan.user.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.xiaomengkuan.common.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Faraj Mujey
 * -- Creation Time: 2021-01-25 4:44 下午, File Encoding: utf8 --
 */
public class SignatureInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        Map<String, Object> map = new HashMap<>();
        try {
            JwtUtil.verify(token);
            return true;
        } catch (TokenExpiredException e) {
            map.put("code", 4300);
            map.put("msg", "token已过期");
        } catch (SignatureVerificationException e) {
            //签名验证
            map.put("code", 4300);
            map.put("msg", "签名验证异常");
        } catch (JWTDecodeException e) {
            map.put("code", 4300);
            map.put("msg", "token解析异常");
        } catch (Exception e) {
            map.put("code", 4300);
            map.put("msg", "token验证异常");
        }
        map.put("status", false);
        response.setContentType("Application/json;charset=UTF-8");
        response.getWriter().println(JSON.toJSON(map));
        return false;
    }
}
